<?php
namespace Customer\Controller;

use Base\Controller\HomeBaseController;

class LoginController extends HomeBaseController {
	
	protected $customerModel;
	
	function _initialize() {
		parent::_initialize();
		
		$this->customerModel = D("Customer/Customer");
	}

    // 注册页面
    public function register() {
    	if (session('CUSTOMER')) {
    		redirect(__ROOT__ . "/");
    	}

    	$this->display(":register");
		return;
    }

    // 认证页面
    public function auth() {
    	$this->display(":auth");
		return;
    }

    // 等待认证页面
    public function authing() {
    	$this->display(":authing");
		return;
    }

    // 登录页面
    public function login() {
    	// session 保存登录信息???
	    $redirect = I('get.redirect', '');
	    if (empty($redirect)) {
	        $redirect = $_SERVER['HTTP_REFERER'];
	    } else {
	        $redirect = base64_decode($redirect);
	    }
	    session('login_http_referer', $redirect);
	    
	    if (session('CUSTOMER')) {
    		redirect(__ROOT__ . "/");
	    }
	    
	    $this->display(":login");
		return;
    }
    
    // ajax判断用户登录状态接口
    function is_login() {
    	if (sp_is_username()) {
    		$this->ajaxReturn(array("status" => 1, "user"=>sp_get_current_user()));
    	} else {
    		$this->ajaxReturn(array("status" => 0,"info"=>"此用户未登录！"));
    	}
    }

    // 退出
    public function logout() {
    	session("CUSTOMER", null);
    	redirect(__ROOT__ . "/");
    }
    
    /*************************************** do **************************************************/
    // doRegister
	public function doRegister() {
	    ////// validate
	    if (!sp_check_verify_code()) {
			$this->assign("messageTitle", "注册失败");
    		$this->error("验证码错误！", U("Customer/Login/register"), 3);
            return;
	    }
	    
	    // validate
        $rules = array(
            //array(验证字段,验证规则,错误提示,验证条件,附加规则,验证时间)
            array('tel', 'require', '手机号不能为空！', 1),
            array('tel', '', '手机号已被注册！！', 0, 'unique', 3),
            array('password', 'require', '密码不能为空！', 1),
            array('password', '5,20', "密码长度至少5位，最多20位！", 1, 'length', 3),
        );
	    if ($this->customerModel->validate($rules)->create() === false) {
			$this->error($this->customerModel->getError());
            return;
	    }
	    
// 	    if (!sp_check_tel_verify_code()) {
// 	        $this->error("手机验证码错误！");
//             return;
//         }

	    ////// add
	    $username = I('post.username');
	    $password = I('post.password');
	    $data = [
	        'username' => $username,
	        'password' => sf_xcms_password($password),
	        'real_name' => '',
	        'tel' => $username,
	        'email' => '',
	        "role" => 0,
	        'status' => 0,
	        'update_time' => date("Y-m-d H:i:s"),
	        'add_time' => date("Y-m-d H:i:s"),
	    ];
	    
	    $result = $this->customerModel->add($data);
	    if (!$result) {
			$this->assign("messageTitle", L('REGISTER_FAILED'));
    		$this->error(L('REGISTER_FAILED'), U("Customer/Login/register"), 3);
            return;
	    }

	    // 注册成功页面跳转
	    $data['id'] = $result;
	    session('CUSTOMER', $data);
	    
	    $this->assign("messageTitle", L('REGISTER_SUCCESS'));
	    $this->success(L('REGISTER_SUCCESS'), __ROOT__ . "/");
	    return;
	}
	
    // 登录验证提交
    public function doLogin() {
	    ////// validate
//     	if (!sp_check_verify_code()) {
// 			$this->assign("messageTitle", L('LOGIN_FAILED'));
//     		$this->error(L('CAPTCHA_NOT_RIGHT'), U("Customer/Login/login"), 3);
//          return;
//     	}
    	
    	// validate
//     	if ($this->customerModel->create() === false) {
//     		$this->error($this->customerModel->getError());
//          return;
//     	}

        ////// login
    	$username = I('post.username');
        $password = I('post.password');
        $where['tel'] = $username;
        $where['_string'] = 'status != -1 AND status != -2';							// 只要不是已删除（-1）和已禁用（-2）用户均可登录 
//      $where = "tel = $username and status ";
        $result = $this->customerModel->where($where)->find();
        if (empty($result)) {
			$this->assign("messageTitle", L('LOGIN_FAILED'));
    		$this->error(L('USERNAME_NOT_EXIST_OR_FORBIDDEN'), U("Customer/Login/login"), 3);
            return;
        }

        // if (sf_xcms_password($password) == $result['password']) {
        if (false) {
            $this->assign("messageTitle", L('LOGIN_FAILED'));
            $this->error(L('CAPTCHA_NOT_RIGHT'), U("Customer/Login/login"), 3);
            return;
        }
        
        session('CUSTOMER', $result);
        // 写入此次登录信息
//         $data = array(
//             'last_login_time' => date("Y-m-d H:i:s"),
//             'last_login_ip' => get_client_ip(0,true),
//         );
//         $this->customerModel->where(array('id' => $result["id"]))->save($data);
//         $session_login_http_referer = session('login_http_referer');
//         $redirect = empty($session_login_http_referer) ? __ROOT__ . "/" : $session_login_http_referer;
//         session('login_http_referer', '');
        
        $this->success("登录成功！", U("Customer/Index/center"));
        return;
    }
	
    // 认证提交
    public function doAuth() {
		$id = $_POST['id'];
		
	    ////// validate
    	$rules = array(
			// array(验证字段,验证规则,错误提示,验证条件,附加规则,验证时间)
			array('role', 'require', '角色必选！'),
			array('real_name', 'require', '姓名不能为空！'),
			array('sex', 'require', '性别不能为空！'),
// 			array('nickname', 'require', '昵称不能为空！'),
			array('id_card', 'require', '身份证号码不能为空！'),
			array('id_card', '/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/', '身份证号不合法！', 1, 'regex', 3),
			array('id_card', '', '身份证号已经存在！', 1, 'unique', 3),
			array('email', 'require', '邮箱不能为空！', 0, 'regex', 3),						// 验证email字段是否为空
			array('email', 'email', '邮箱格式不正确！', 0, '', 3),							// 验证email字段格式是否正确
			array('email', '', '邮箱帐号已经存在！', 0, 'unique', 3),							// 验证email字段是否唯一
			array('auth_file', 'require', '验证文件不能为空！'),
    	);
    	if ($this->customerModel->validate($rules)->create() === false) {
    		$this->error($this->customerModel->getError());
            return;
    	}

    	////// update
		$customer['role'] = I('post.role');
		$customer['real_name'] = I('post.real_name');
		$customer['sex'] = I('post.sex');
// 		$customer['nickname'] = I('post.nickname');
		$customer['id_card'] = I('post.id_card');
		$customer['email'] = I('post.email');
		$customer['auth_file'] = I('post.auth_file');
		$customer['status'] = 3;										// 等等认证中...
		$customer['update_time'] = date("Y-m-d H:i:s");
		
		// 执行更新
		$result = $this->customerModel->where(array("id" => $id))->save($customer);
		if (false === $result) {
    		$this->error("提交失败，请联系管理员处理！", U("Customer/Login/auth"));
            return;
		}

		$updatedCustomer = $this->customerModel->where(array("id" => $id))->find();
		$this->success("提交成功，请等待管理员认证！", U("Content/Index/index"));
		return;
    }
    
    /*************************************** wx **************************************************/
    // doRegister
	public function doWxRegister() {
	    ////// validate
        $rules = array(
            //array(验证字段,验证规则,错误提示,验证条件,附加规则,验证时间)
            array('real_name', 'require', '姓名不能为空！', 1),
            array('tel', 'require', '手机号不能为空！', 1),
            array('tel', '', '手机号已被注册！！', 0, 'unique', 3),
        );
	    if ($this->customerModel->validate($rules)->create() === false) {
			$data['code'] = 499;
			$data['msg'] = '注册失败，' . $this->customerModel->getError();
			$this->ajaxReturn($data);
	    }
	    
// 	    if (!sp_check_tel_verify_code()) {
// 			$data['code'] = 499;
// 			$data['msg'] = '手机验证码错误！';
// 			$this->ajaxReturn($data);
//      }

	    ////// add
	    $real_name = I('post.real_name');
	    $tel = I('post.tel');
	    $avatar = I('post.avatar');
	    $sex = I('post.sex');
	    $open_id = I('post.open_id');
	    $item = [
	        'username' => '',//$username,
	        'password' => '',//sf_xcms_password($password),
	        'real_name' => $real_name,
	        'tel' => $tel,
	        'avatar' => $avatar,
	        'sex' => $sex,
	        "open_id" => $open_id,
	        'email' => '',
	        "role" => 1,           // 角色 1: 普通客户, 2: 员工（后期可删）
	        'status' => 1,         // 免审
	        'add_time' => date("Y-m-d H:i:s"),
	        'update_time' => date("Y-m-d H:i:s"),
	    ];
	    
	    $result = $this->customerModel->add($item);
	    if (!$result) {
			$data['code'] = 499;
			$data['msg'] = L('REGISTER_FAILED');
			$this->ajaxReturn($data);
	    }

	    // 注册成功页面跳转
	    $item['id'] = $result;
        
	    $data['code'] = 0;
	    $data['msg'] = L('REGISTER_SUCCESS');
	    $data['obj'] = $item;
	    $this->ajaxReturn($data);
	}

}
